var operateItem = '';
//每页的最大数量
var itemMax = 6;
//当前页面
var nowPage = 1;
var firstItem = itemMax * (nowPage - 1);
var lastItem = itemMax * (nowPage);
//判断添加的部门内容是否有错（若有错不能提交）
var addDepItem = {
	'name': false,
	'leading':false
}

//判断编辑的部门内容是否有错（若有错不能提交）				
var isExist=false;
var leaderExist=true;
var addDepJson = {};
// var editDepJson = {};
var getArr = JSON.parse(localStorage.getItem('departmentJson'));
//获取员工数组
var getStaffArr=JSON.parse(localStorage.getItem('staff'));
//统计每个部门的员工数
function countNum(name){
	var num=0;
    $.each(getStaffArr,function(index,value){
		if(value.department==name){
			num++;
		}
	})
	return num;
	
}
$.each(getArr, function(index, value) {
	if (index >= firstItem && index < lastItem) {
		createList($('.table1'), index, value);
	}
})

//创建分页
createPage();

function createPage() {
	var read = JSON.parse(localStorage.getItem('departmentJson'));
	$('.pagination').append('<li><a href="javascript:;" id="leftPage"><span style="font-size: 14px;">&laquo;</span></a></li>');
	for (var i = 0; i < Math.ceil(read.length / itemMax); i++) {
		
			$('.pagination').append('<li><a href="javascript:;" class="pageNum" id="' + (i + 1) + '">' + (i + 1) + '</a></li>');
		
	}
	$('.pagination').append('<li><a href="javascript:;" id="rightPage"><span style="font-size: 14px;">&raquo;</span></a></li>');
	
}

function createList(obj, index, value) {
	$('.table1').append('<tr id="' + value.name + '"><td>' + (index + 1) + '</td><td>' + value.name + '</td><td>' + value.leading +
		'</td><td>' +
		value.leadingTel +
		'</td><td>' + countNum(value.name) + '</td><td>' + value.about +
		'</td><td><div class="department-operate">' +
		'<button type="button" class="btn btn-primary btn-sm edit" name="edit" data-toggle="modal" data-target="#departmentEdit">编辑</button>' +
		'<button type="button" class="btn btn-warning btn-sm delete" name="delete" data-toggle="modal" data-target="#departmentDelete">删除</button>' +
		'</div></td><td><button type="button" class="btn btn-primary btn-sm" name="check" data-toggle="modal" data-target="#DepartmentCheck">查看人员</button></td>'
	);
}
$('.pagination').children().eq(1).addClass('active');
//为分页添加事件
$('.pagination').on('click', 'a', function() {
	if ($(this).attr('id') == 'leftPage') {
		if ($('.pageNum[id=' + nowPage + ']').parent().prev().children().eq(0).attr('id') != 'leftPage') {
			$(this).parent().removeClass('disabled');
			nowPage -= 1;
			$('.active').removeClass('active')
			$('.pagination').children().eq(nowPage).addClass('active');
			$("tr:not('.headline')").remove();
			firstItem = itemMax * (nowPage - 1);
			lastItem = itemMax * (nowPage);
			var read = JSON.parse(localStorage.getItem('departmentJson'));
			$.each(read, function(index, value) {
				if (index >= firstItem && index < lastItem) {
					createList($('.table1'), index, value);
				}
			})
		}else{
			$(this).parent().addClass('disabled','disabled');
		}
	} else if ($(this).attr('id') == 'rightPage') {
		if ($('.pageNum[id=' + nowPage + ']').parent().next().children().eq(0).attr('id') != 'rightPage') {
			$(this).parent().removeClass('disabled');
			nowPage += 1;
			$('.active').removeClass('active')
			$('.pagination').children().eq(nowPage).addClass('active');
			$("tr:not('.headline')").remove();
			firstItem = itemMax * (nowPage - 1);
			lastItem = itemMax * (nowPage);
			var read = JSON.parse(localStorage.getItem('departmentJson'));
			$.each(read, function(index, value) {
				if (index >= firstItem && index < lastItem) {
					createList($('.table1'), index, value);
				}
			})
		}else{
			$(this).parent().addClass('disabled','disabled');
		}
	} else {

		$("tr:not('.headline')").remove();
		nowPage = parseInt($(this).attr('id'));
		firstItem = itemMax * (nowPage - 1);
		lastItem = itemMax * (nowPage);
		$('.active').removeClass('active')
		$('.pagination').children().eq(nowPage).addClass('active');
		var read = JSON.parse(localStorage.getItem('departmentJson'));
		$.each(read, function(index, value) {
			if (index >= firstItem && index < lastItem) {
				createList($('.table1'), index, value);
			}
		})
	}
});



//为编辑 删除 查看人员添加事件（记录操作的是哪一行）
$('.table1').on('click', 'button', function() {
	//指定将要操作哪行
	operateItem = $(this).parents('tr').attr('id');
    if($(this).attr('name')=='check'){
		$('.checkList').remove();
		$('.checkbody p').remove();
	 var read = JSON.parse(localStorage.getItem('staff'));	
	 var num=0;
	 $.each(read,function(index,value){
		 if(value.department==operateItem){
			  $('.table2').append('<tr class="checkList"><td>'+value.name
			                      +'</td><td>'+value.sex
								  +'</td><td>'+value.post
								  +'</td><td>'+value.Tel
								  +'</td><td>'+value.birthday
								  +'</td></tr>');
			  num++;				  
		 }
	 })
	if(num==0){
		$('.checkList').remove();
		$('.checkbody').append('<p style="text-align: center;">该部门暂时无部门人员</p>');
	}
	}
	if($(this).attr('name')=='edit'){
		$('input[name="name"]').val($(this).parents('tr').children().eq(1).text());
		$('input[name="leading"]').val($(this).parents('tr').children().eq(2).text());
		$('input[name="leadingTel"]').val($(this).parents('tr').children().eq(3).text());
		$('input[name="about"]').val($(this).parents('tr').children().eq(5).text());
		$('.DepartmentRemind').css('display','none');
		leaderExist=true;
		}
	
});
//为模态框departmentDelete 确定按钮添加事件
$('#deletesResure').on('click', function() {
	if($('tr[id='+operateItem+']').children().eq(4).text()!=0){
		alert('该部门人数不为0，删除失败！');
		return;
		
	}


	$("tr:not('.headline')").remove();
	removeJson(operateItem);
	var read = JSON.parse(localStorage.getItem('departmentJson'));
	$('#departmentDelete').modal('hide');
	
	
	$('.pagination').children().remove();
	createPage();
	if(nowPage!=Math.ceil(read.length/itemMax)&&nowPage>Math.ceil(read.length/itemMax)){
		nowPage-=1;
		$('.active').removeClass('active')
		$('.pagination').children().eq(nowPage).addClass('active');
		firstItem = itemMax * (nowPage - 1);
		lastItem = itemMax * (nowPage);
		$.each(read, function(index, value) {
			if (index >= firstItem && index < lastItem) {
				createList($('.table1'), index, value);
			}
		})
	}else{
		$('.active').removeClass('active')
		$('.pagination').children().eq(nowPage).addClass('active');
		firstItem = itemMax * (nowPage - 1);
		lastItem = itemMax * (nowPage);
		$.each(read, function(index, value) {
			if (index >= firstItem && index < lastItem) {
				createList($('.table1'), index, value);
			}
		})
	}
	itemResort(nowPage);
	
})

//为模态框departmentEdit 确定按钮添加事件
$('#saveEdit').on('click', function() {
	var name=$('input[name="name"]').val();
	var leading=$('input[name="leading"]').val();
	var leadingTel=$('input[name="leadingTel"]').val();
	var about=$('input[name="about"]').val();
	console.log(getRegMsg('name').test(name));
	console.log(getRegMsg('leading').test(leading));
	console.log(getRegMsg('leadingTel').test(leadingTel));
	console.log(getRegMsg('about').test(about));
	console.log(isExist);
	console.log(leaderExist)
	if(getRegMsg('name').test(name)&&getRegMsg('leading').test(leading)&&getRegMsg('leadingTel').test(leadingTel)&&getRegMsg('about').test(about)&&isExist==false&&leaderExist){
	
	
	var read = JSON.parse(localStorage.getItem('departmentJson'));
	$("tr:not('.headline')").remove();
	$.each(read, function(index, value) {
		if (value.name == operateItem) {
			value.name = name;
			value.leading = leading;
			value.leadingTel = leadingTel;
			value.about = about;
		}
		firstItem = itemMax * (nowPage - 1);
		lastItem = itemMax * (nowPage);
		if (index >= firstItem && index < lastItem) {
			createList($('.table1'), index, value);
		}
	})
	itemResort(nowPage);
	localStorage.setItem("departmentJson", JSON.stringify(read));
	
	$('input[name="name"]').val('');
	$('input[name="leading"]').val('');
	$('input[name="leadingTel"]').val('');
	$('input[name="about"]').val('');
	$('#departmentEdit').modal('hide');
	}else{
		alert('添加错误或未添加完全！');
	}
})

//检测departmentEdit input 输入值是否输入正确
$('.departmentEditInput').on('input', function() {
	        isExist=false;
			leaderExist=true;
			var itemsName = $(this).attr('name');
			var itemsValue = $(this).val();
			var reg = getRegMsg(itemsName);
			var read = JSON.parse(localStorage.getItem('departmentJson'));
			var staff=JSON.parse(localStorage.getItem('staff'));
			var textValue = $('.departmentEditInput').eq(0).val();
			var leadingName=$('.departmentEditInput').eq(1).val();
			var that = $(this)
			if (!reg.test(itemsValue)) {
				$(this).parent().next().next().css('display', 'block');
			} else {
				$(this).parent().next().next().css('display', 'none');
			}
		if (that.attr('name')=='name') {
			$.each(read, function(index, value) {
						if (value.name == textValue 
						 && value.name != operateItem) {
							that.parent().next().next().text('该部门已存在');
							that.parent().next().next().css('display', 'block');
							isExist=true;
							return false;
						} else {
							if (reg.test(itemsValue)) {
								that.parent().next().next().css('display', 'none');
								isExist=false;
							} else {
								that.parent().next().next().text('部门名称长度在3-10字之间!');
								isExist=false;
							}
						}
					})
					
			}
			if (that.attr('name')=='leading') {
			$.each(staff, function(index, value) {
						if (value.name==leadingName) {
							that.parent().next().next().css('display', 'none');
						    $('.departmentEditInput').eq(2).val(value.Tel);
							leaderExist=true;
							return false;
						} else {
							if (reg.test(itemsValue)) {
								that.parent().next().next().text('本幼儿园不存在该员工！');
								that.parent().next().next().css('display', 'block');
								leaderExist=false;
							} else {
								that.parent().next().next().text('负责人名称长度在2-10字之间！');
								that.parent().next().next().css('display', 'block');
								leaderExist=false;
							}
						}
					})
					
			}
			})
		//重新排序函数
		function itemResort(page) {
			for (var i = 0; i < $('.table1').children().children().length; i++) {
				if (i >= 1) {
					$('.table1').children().children().eq(i).children().eq(0).text((page-1)*6+i);
				}
			}
		}
		//删除对应JSON(以部门名称作为主键)
		function removeJson(name) {

			var removeName = name;
			var read = JSON.parse(localStorage.getItem('departmentJson'));
			$.each(read, function(index, value) {
				if (value.name == removeName) {
					read.splice(index, 1);
					localStorage.setItem("departmentJson", JSON.stringify(read));
					return false;
				}
			})
		}
		//判断输入值是否符合正则，同时将正确的输入值传入将要添加进部门数组的json
		$('.addDepartmentInput').on('input', function() {
			var itemsName = $(this).attr('id')
			var itemsValue = $(this).val();
			var reg = getRegMsg(itemsName);
			var read = JSON.parse(localStorage.getItem('departmentJson'));
			var staff= JSON.parse(localStorage.getItem('staff'));
			var textValue = $('.addDepartmentInput').eq(0).val();
			var that = $(this);
			if (reg.test(itemsValue)) {
				$(this).parent().next().next().css('display', 'none');
			} else {
				$(this).parent().next().next().css('display', 'block');
			}
			if(that.attr('id')=='name'){
			$.each(read, function(index, value) {
				if (value.name == textValue) {
					that.parent().next().next().text('该部门已存在');
					that.parent().next().next().css('display', 'block');
					addDepItem['name'] = false;
					return false;
				} else {
					if (reg.test(itemsValue)) {
						that.parent().next().next().css('display', 'none');
						addDepItem['name'] = true;
					} else {
						that.parent().next().next().text('部门名称长度在3-10字之间!');
						addDepItem['name'] = false;
					}
				}
				})
			}
			if (that.attr('id')=='leading') {
			$.each(staff, function(index, value) {
						if (value.name==itemsValue) {
							that.parent().next().next().css('display', 'none');
						    $('#leadingTel').val(value.Tel);
							addDepJson['leadingTel']=value.Tel;
							addDepItem['leading']=true;
							return false;
						} else {
							if (reg.test(itemsValue)) {
								that.parent().next().next().text('本幼儿园不存在该员工！');
								that.parent().next().next().css('display', 'block');
								addDepItem['leading']=false;
							} else {
								that.parent().next().next().text('负责人名称长度在2-9字之间！');
								that.parent().next().next().css('display', 'block');
							}
						}
					})
			}
			
		})

		//获取对应正则（以input id为函数参数）
		function getRegMsg(name) {
			var reg = '';
			switch (name) {
				case 'name':
					reg = depNameReg;
					break;
				case 'leading':
					reg = nameReg;
					break;
				case 'leadingTel':
					reg = phoneNumberReg;
					break;
				case 'about':
					reg = depDetailsReg;
					break;
			}
			return reg;
		}
   $('#addDep').on('click',function(){

	   $('#name').val('');
	   $('#leading').val('');
	   $('#leadingTel').val('');
	   $('#about').val('');
	   $('.DepartmentRemind').css('display','none');
   })
		//保存添加的部门
		$('#saveDep').on('click', function() {
			var name=$('#name').val();
			var leading=$('#leading').val();
			var leadingTel=$('#leadingTel').val();
			var about=$('#about').val();
			if(getRegMsg('name').test(name)&&getRegMsg('leading').test(leading)&&getRegMsg('leadingTel').test(leadingTel)&&getRegMsg('about').test(about)&&addDepItem['name']&&addDepItem['leading']){
			var read = JSON.parse(localStorage.getItem('departmentJson'));
			addDepJson['name']=name;
			addDepJson['leading']=leading;
			addDepJson['leadingTel']=leadingTel;
			addDepJson['about']=about;
			read.unshift(addDepJson);
			$("tr:not('.headline')").remove();
			nowPage=1;
			firstItem = itemMax * (nowPage - 1);
			lastItem = itemMax * (nowPage);
			$.each(read, function(index, value) {
				if (index >= firstItem && index < lastItem) {
					createList($('.table1'), index, value);
				}
			})
			itemResort(nowPage);
			localStorage.setItem("departmentJson", JSON.stringify(read));
		    $('#name').val('');
			$('#leading').val('');
			$('#leadingTel').val('');
			$('#about').val('');
			$('#addDepartmentModal').modal('hide');
			$('.pagination').children().remove();
			createPage();
			$('.active').removeClass('active')
			$('.pagination').children().eq(nowPage).addClass('active');
			}else{
				alert('输入有误！');
			}
		})
